package com.yixun.service.impl;

import com.alibaba.fastjson.JSON;
import com.yixun.entity.YxMenu;
import com.yixun.entity.YxUser;
import com.yixun.mapper.MenuMapper;
import com.yixun.service.LogSetService;
import com.yixun.service.MenuService;
import com.yixun.service.RedisService;
import com.yixun.util.LogUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MenuServiceImpl implements MenuService {

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private LogSetService logSetService;

    @Override
    public List<YxMenu> getMenuListByUserId(String userId) {

        return menuMapper.getMenuListByUserId(userId);
    }


    @Override
    public List<YxMenu> getChildMenuListByID(List<YxMenu> menuList, String menu_id) {
        List<YxMenu> childMenuList = new ArrayList<>();
        for (YxMenu mb: menuList) {
            if (menu_id.equals(mb.getParent_id()+"")) {
                childMenuList.add(mb);
            }
        }
        return childMenuList;
    }

    @Override
    public String getMenuTree(String menu_id) {
        List<YxMenu> all_list = menuMapper.getAllMenuList();
        YxMenu menu = menuMapper.getMenuBean(menu_id);
        if (null != menu) {
            String json_str = "[{\"id\":" + menu.getMenu_id() + ",\"text\":\""
                    + menu.getMenu_name()+ "\",\"attributes\":{}";
            String child_str = getAllMenuTreeHandle(all_list,getChildMenuListByID(all_list,menu.getMenu_id()+""));
            if (null != child_str && !"".equals(child_str)) {
                json_str += ",\"children\":[" + child_str + "]";
            }
            json_str += "}]";
            return json_str;
        } else {
            return "[]";
        }
    }

    @Override
    public List<YxMenu> getChildMenuList(String menu_id) {
        List<YxMenu> all_list = menuMapper.getAllMenuList();
        List<YxMenu> child_menu_list = new ArrayList<>();
        for (YxMenu menu: all_list) {
            if (menu_id.equals(menu.getParent_id() + "")) {

                child_menu_list.add(menu);
            }
        }
        return child_menu_list;
    }

    @Override
    @Transactional
    public int insertMenu(YxUser sessionUser, YxMenu menu) {
        int row = 0;
        YxMenu parentMenu = menuMapper.getMenuBean(menu.getParent_id() + "");
        Long menu_id = redisService.incr("menu_id", 1L);
        menu.setMenu_id(menu_id);
        menu.setMenu_position(parentMenu.getMenu_position() + menu_id + "$");
        row = menuMapper.insertMenu(menu);
        if (row == 1) {
            logSetService.insertSettingLogs(LogUtil.ADD, "菜单", JSON.toJSONString(menu), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    public YxMenu getMenuBean(String menu_id) {
        return menuMapper.getMenuBean(menu_id);
    }

    @Override
    @Transactional
    public int updateMenu(YxUser sessionUser, YxMenu menu) {
        int row = 0;
        row = menuMapper.updateMenu(menu);
        if (row == 1) {
            logSetService.insertSettingLogs(LogUtil.UPDATE,"菜单", JSON.toJSONString(menu), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    @Transactional
    public int delMenu(YxUser sessionUser, String id) {
        int row = 0;
        String[] ids = id.split(",");
        for (String menu_id: ids) {
            String menu_position = menuMapper.getMenuPositionByMenuId(menu_id);
            menuMapper.delMenuAndChild(menu_position);
            row++;
        }
        if (row > 0) {
            logSetService.insertSettingLogs(LogUtil.DELETE,"菜单", JSON.toJSONString(id), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    @Transactional
    public int moveMenu(YxUser sessionUser, String parent_id, String menu_ids) {
        int row = 0;
        String parent_menu_position = menuMapper.getMenuPositionByMenuId(parent_id);
        if (null != menu_ids && !"".equals(menu_ids)) {
            String[] ids = menu_ids.split(",");
            for (int i =0; i < ids.length; i++) {
                moveMenuHandle(ids[i], parent_id, parent_menu_position);
                row++;
            }
        }
        if (row > 0) {
            logSetService.insertSettingLogs(LogUtil.MOVE,"菜单", JSON.toJSONString(parent_id + "--" + menu_ids), sessionUser);
            return row;
        }
        return row;
    }

    @Override
    @Transactional
    public int sortMenu(YxUser sessionUser, String id) {
        int row = 0;
        String[] ids = id.split(",");
        Map<String,String> m = new HashMap<>();
        for (int i= 0; i < ids.length; i++) {
            m.put("menu_id", ids[i]);
            m.put("menu_sort", (i+1) + "");
            menuMapper.sortMenu(m);
            row++;
        }
        if (row > 0) {
            logSetService.insertSettingLogs(LogUtil.SAVE_SORT,"菜单", JSON.toJSONString(id), sessionUser);
            return row;
        }
        return row;
    }


    /*=======================================moveMenuHandle===============================================*/

    public void moveMenuHandle(String menu_id, String parent_id, String parent_menu_position){
        String menu_position = parent_menu_position + menu_id + "$";
        Map<String, String> map = new HashMap<>();
        map.put("menu_id",menu_id);
        map.put("parent_id", parent_id);
        map.put("menu_position", menu_position);

        if (menuMapper.moveMenu(map) > 0) {
            // 该节点下的子节点一并转移
            List<YxMenu> child_list = getChildMenuList(menu_id);
            if (null != child_list && child_list.size() > 0) {
                for (YxMenu child: child_list) {
                    moveMenuHandle(child.getMenu_id() + "", menu_id, menu_position);
                }
            }
        }
    }

    /*=======================================moveMenuHandle===============================================*/



    /*=======================================MENU_Tree_Util===============================================*/

    public String getAllMenuTreeHandle(List<YxMenu> all_list, List<YxMenu> dl){
        String json_str = "";
        String show_status = "";
        if (null != dl && dl.size() > 0) {
            for (YxMenu menu: dl) {
                show_status ="";
                json_str += ",{";
                json_str += "\"id\":" + menu.getMenu_id() + ","
                        + "\"text\":\"" + menu.getMenu_name()
                        + "\",\"attributes\":{}";
                List<YxMenu> child_m_list = getChildMenuListByID(all_list,menu.getMenu_id()+ "");
                if (null != child_m_list && child_m_list.size() > 0) {
                    json_str += show_status;
                    json_str +=",\"children\":["+ getAllMenuTreeHandle(all_list,child_m_list) + "]";
                }
                json_str += "}";
            }
            if (json_str != null && !"".equals(json_str)){
                json_str = json_str.substring(1);
            }
        }
        return json_str;
    }

    /*=======================================MENU_Tree_Util===============================================*/
}
